package pro;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
 
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
 
/**
 * 要实现单例模式，保证全局只有一个数据库连接池
 * @author pelin
 *
 * 2018年03月23日
 */
public class DBPoolConnection {
    private static DBPoolConnection dbPoolConnection = null;
    private static DruidDataSource druidDataSource = null;
    
    static {
    	Properties properties = PathUtil.getProperties();
        try {
        	//DruidDataSrouce工厂模式
            druidDataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 数据库连接池单例
     * @return
     */
    public static synchronized DBPoolConnection getInstance(){
        if (null == dbPoolConnection){
            dbPoolConnection = new DBPoolConnection();
        }
        return dbPoolConnection;
    }
    
    /**
     * 返回druid数据库连接
     * @return
     * @throws SQLException
     */
    public DruidPooledConnection getConnection() throws SQLException{
        return druidDataSource.getConnection();
    }
    
    public static void main(String[] args) {
    	//执行一条sql语句测试
    	DBPoolConnection dbp = DBPoolConnection.getInstance();    //获取数据连接池单例
        DruidPooledConnection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
        	String sql = "insert into TBL_CALL_LOG ("
        			+ "CALLID, CALLER, ACCOUNTSID, APPID, REASON, MULTICALLED,"
        			+ "STATE, NUMBER, TYPE, WORKNUMBER, RINGDURATION, SWITCHNUMBER,"
        			+ "CALLED, MOBILE, CALLTYPE, STARTTIME, STOPTIME, DURATION,"
        			+ "TASKID, BATCHID, USERDATA"
        			+ ") values ("
        			+ "?, ?, ?, ?, ?, ?, "
        			+ "?, ?, ?, ?, ?, ?, "
        			+ "?, ?, ?, ?, ?, ?, "
        			+ "?, ?, ?"
        			+ ")";
            conn = dbp.getConnection();    //从数据库连接池中获取数据库连接
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()) {
            	System.out.println(rs.getObject("id").toString() + "," + rs.getObject("value").toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
            	if (null != rs){
            		rs.close();
                }
                if (null != ps){
                    ps.close();
                }
                if (null != conn){
                    conn.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
	}
}
